<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>用async/await 来处理异步</title>
</head>
<body>
	
	<input type="text" id="phone">
	<button id="btn">确定</button>
	<div id="result"></div>

	<script src="jquery-3.2.1.min.js"></script>
	<script>
		/*$("#btn").click(function(){
			let phone = $.trim($("#phone").val());
			console.log(phone);

			$.ajax({
				type: "POST",
				url: "http://127.0.0.1/PHPStudy/async/async.php",
				dataType: "json",
				data: {"phone":phone},
				success:function(res){
					console.log(res.msg, res.num);
				
					$("#result").html(res.msg);

					$.ajax({
						type: "POST",
						url: "http://127.0.0.1/PHPStudy/async/async.php",
						dataType: "json",
						data: {"num": res.num},
						success:function(res){
							console.log(res.msg, res.num);

							$("#result").html(res.msg);
						},
						error:function(msg){
							console.log("ERROR:",msg);
						}
					});
				},
				error:function(msg){
					console.log("ERROR:",msg);
				}
			});
		});*/
	</script>
	<script>
		/*const postRequest = function(url, data){
			return new Promise((resolve, reject) => {
				$.ajax({
					type: 'POST',
					url: url,
					dataType: "json",
					data: data,
					success: function(res){
						resolve(res);
					},
					error: function(error){
						reject(error);
					}
				});
			});
		};
		$("#btn").click(function(){
			let phone = $.trim($("#phone").val());
			console.log(phone);

			postRequest("http://127.0.0.1/PHPStudy/async/async.php", {"phone":phone})
			.then(res => {
				console.log(res.msg, res.num);
				$("#result").html(res.msg);

				return postRequest("http://127.0.0.1/PHPStudy/async/async.php", {"num": res.num});
			}).then(res => {
				console.log(res.msg, res.num);
				$("#result").html(res.msg);
			}).catch(err => {
				console.log("ERROR:",err);
			})
		});*/
	</script>
	<script>
		function postRequest(url, data){
			return new Promise((resolve, reject) => {
				$.ajax({
					type: 'POST',
					url: url,
					dataType: "json",
					data: data,
					success: function(res){
						resolve(res);
					},
					error: function(error){
						reject(error);
					}
				});
			});
		};

		$("#btn").click(async function(){
			let phone = $.trim($("#phone").val());
			console.log(phone);
			try{
				let p1 = await postRequest("http://127.0.0.1/PHPStudy/async/async.php", {"phone":phone});
				console.log(p1);
				$("#result").html(p1.msg);

				let p2 = await postRequest("http://127.0.0.1/PHPStudy/async/async.php", {"num": p1.num});
				console.log(p2);
				$("#result").html(p2.msg);

			}catch(e){
				console.log(e);
			}
		});
	</script>
</body>
</html>